package org.example.Filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.CurrentHolder;
import org.example.utils.JwtUtils;

import java.io.IOException;
import java.net.HttpURLConnection;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter  implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  (HttpServletRequest) servletRequest;//获取请求
        HttpServletResponse response = (HttpServletResponse) servletResponse;//获取响应
        //获取请求路径
        String requestURI = request.getRequestURI(); //uri只包含请求路径  /login/login
        //判断是否是登录请求
        if ( requestURI.contains("/login")) {
            //放行
            log.info("登陆操作  放行");
            filterChain.doFilter(servletRequest,servletResponse);//放行
        } else {
            //获取请 求头中的token
            String token = request.getHeader("token");
            //判断token是否为空
            if (token == null || token.isEmpty()) {//token为空 用户未登陆 返回错误信息（响应错误码401）
                //响应错误信息
                log.info("token为空 ,响应401");
                response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
            }else {//token不为空 校验
                try {
                    Claims claims =JwtUtils.parseToken(token);//解析token
                    int empId = Integer.parseInt(claims.get("id").toString());
                    CurrentHolder.setCurrentId(empId);//设置当前线程绑定的id
                    log.info("token校验成功 ,当前登陆员工：ID:"+empId);
                    filterChain.doFilter(servletRequest,servletResponse);//放行
                }catch(Exception e){
                    log.info("token校验失败 ,响应401");
                    response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
                }

            }
        }
        //删除当前线程绑定的id
        CurrentHolder.remove();

    }


}
